<?php

namespace app\api\controller;

use app\admin\model\Appfuns;
use app\admin\model\UserMoneyLog;
use app\common\controller\Frontend;

class Orders extends Frontend
{
    protected array $noNeedPermission = ["*"];

    /* *
       商家接单列表在线充值订单
    */
    public function oncharge()
    {
        error_reporting(0);
        if ($this->auth->group_id != 2) {
            $this->success('查询订单', ['data' => []]);
        }
        $map = [];
        $appfun_id = $this->request->param('appfuns_id/d');
        $keyword = $this->request->param('keyword/s');
        if ($appfun_id >= 0) {
            $map[] = ['appfuns_id', 'in', $appfun_id];
        }
        if ($keyword) {
            $map[] = ['order_no', 'like', '%' . $keyword . '%'];
        }
        $status = $this->request->param('status/d');
        $o_type = $this->request->param('o_type', 'opt1');
        if ($o_type) {
            $map[] = ['radio', '=', $o_type];
        }
        if($this->request->param('action','')=='master_id'){
            $map[] = ['master_id', '=', $this->auth->id];
            if($status!=4){
                $map[] = ['status', '=', $status];
            }
        }else{
            $map[] = ['status', '=', 0];
            $map[] = ['assign_status', '=', 0];
        }
        $result = (new \app\admin\model\Orders())
            ->where($map)
            ->order('status', 'ASC')
            ->with(['business', 'appfuns', 'user'])
            ->paginate();
        $result->visible([
            'appfuns' => ['name'],
            'business' => ['title'],
            'user' => ['username']
        ]);
        $this->success('在线充值订单', $result);
    }

    /**
     * 生活订单
     */
    public function index()
    {
        error_reporting(0);
        if ($this->auth->group_id != 2) {
            $this->success('生活订单', []);
            $this->error('暂无权限');
        }
        $map = [];
        $appfun_id = $this->request->param('appfun_id/d');
        $keyword = $this->request->param('keyword/s');
        if ($appfun_id) {
            $map[] = ['appfuns_id', '=', $appfun_id];
        }
        if ($keyword) {
            $map[] = ['order_no', 'like', '%' . $keyword . '%'];
        }
        $status = $this->request->param('status/d');
        $o_type = $this->request->param('o_type', 'opt1');
        if ($o_type) {
            $map[] = ['radio', '=', $o_type];
        } else {
            $map[] = ['radio', 'in', ['opt2', 'opt3', 'opt4']];
        }
        if ($status >= 0 && $status < 4) {
            $map[] = ['status', '=', $status];
        }
        $result = (new \app\admin\model\Orders())
            ->where($map)
            ->order('status', 'ASC')
            ->with(['business', 'appfuns', 'user'])
            ->paginate();
        $result->visible([
            'appfuns' => ['name'],
            'business' => ['title'],
            'user' => ['username']
        ]);
        $this->success('生活订单', $result);
    }


    /**
     * 个人的下单列表
     * */
    public function myorder()
    {
        $map = [];
        $appfun_id = $this->request->param('appfun_id/d');
        $keyword = $this->request->param('keyword/s');
        if ($keyword) {
            $map[] = ['order_no', 'like', '%' . $keyword . '%'];
        }
        //$status = $this->request->param('status/d');
        $assign_status = $this->request->param('checkstatus/d');
        $o_type = $this->request->param('o_type', 'opt1');
        if ($o_type) {
            $map[] = ['radio', '=', $o_type];
        }
        if ($assign_status >= 0) {
            $map[] = ['check_status', '=', $assign_status];
        }
        $map[] = ['user_id', '=', $this->auth->id];
        $result = (new \app\admin\model\Orders())
            ->where($map)
            ->order('id', 'desc')
            ->with(['business', 'appfuns', 'user', 'masters'])
            ->paginate()
            ->each(function ($item, $key) {
                $textarea = json_decode($item['textarea'], true);
                $formapp = [];
                if (!empty($textarea) && count($textarea) > 0) {
                    foreach ($textarea as $k => $v) {
                        $formapp[] = ['title' => $v['name'], 'value' => $v['value']];
                    }
                }
                $item['formappa'] = $formapp;
                return $item;
            });
        $result->visible([
            'appfuns' => ['name'],
            'business' => ['title'],
            'user' => ['username']
        ]);
        $result = [
            'current_page' => $result->currentPage(),
            'data' => $result->items(),
            'last_page' => $result->lastPage(),
            'per_page' => $result->listRows(),
            'total' => $result->total(),
            'site_tel' => get_sys_config('site_tel'),
            'userinfo' => $this->auth->getUserInfo()
        ];
        $this->success('查询订单', $result);
    }

    public function upstatus()
    {
        $status = $this->request->param('status');
        $action = $this->request->param('action');
        $order_id = $this->request->param('order_id');
        $row = (new \app\admin\model\Orders())
            ->where('id', '=', $order_id)
            ->find();
        if (!$row) {
            $this->error('订单不存在');
        }
        if (!in_array($action, ['assign_status', 'status', 'check_status'])) {
            $this->error('操作不存在');
        }
        if ($action == 'check_status') {
            if ($row['user_id'] != $this->auth->id) {
                $this->error('订单权限不足');
            }
            $settle_rate = (new Appfuns())->where('id', '=', $row['appfuns_id'])->value('settle_rate');
            if (empty($settle_rate)) {
                $settle_rate = get_sys_config('settle_rate');
            }
            (new UserMoneyLog())->save([
                'money' => bcmul($row['pay_dollar'], $settle_rate / 100),
                'memo' => '确定订单完成_' . $order_id,
                'user_id' => $row['master_id'],
                'create_time' => time(),
            ]);
            $noinfo = (new \app\admin\model\User())
                ->where('id', '=', $row['master_id'])
                ->find();
            $noinfo->save([
                'unmoney' => $noinfo['unmoney'] - $row['pay_dollar']
            ]);
        }
        $uparr = [
            $action => $status
        ];
        //
        if($status==2&&$this->auth->id==$row['master_id']){
            if($row['status']==2){
                $this->error('该订单已完成过',$uparr);
            }
        }
        //overimg
        $overimg = $this->request->param('overimg');
        if (!empty($overimg)) {
            $uparr['overimg'] = $overimg;
            $uparr['check_status'] = 0;
        }
        $row->save($uparr);
        $this->success('确认完成成功');
    }

    /*查询订单*/
    public function cxorder()
    {
        $map = [];
        $appfun_id = $this->request->param('appfun_id/d');
        $keyword = $this->request->param('keyword/s');
        if ($appfun_id) {
            $map[] = ['appfuns_id', '=', $appfun_id];
        }
        if ($keyword) {
            $map[] = ['order_no', 'like', '%' . $keyword . '%'];
        }
        $status = $this->request->param('status/d');
        $o_type = $this->request->param('o_type', 'opt0');
        if ($o_type) {
            $map[] = ['radio', '=', $o_type];
        }
        if ($status >= 0 && $status < 4) {
            $map[] = ['cxstatus', '=', $status];
        }
        $map[] = ['user_id', '=', $this->auth->id];
        $result = (new \app\admin\model\Orders())
            ->where($map)
            ->with(['business', 'user'])
            ->paginate();
        $result->visible([
            'appfuns' => ['name'],
            'business' => ['title'],
            'user' => ['username']
        ]);
        $this->success('查询订单', $result);
    }
    /**
     * 订单转换
     */


    /*接单操作*/
    public function getOrders()
    {
        error_reporting(0);
        $id = $this->request->param('id/d');
        $order_id = $this->request->param('order_id/d');
        $order_id = empty($id) ? $order_id : $id;
        if ($this->auth->group_id == 2) {
            $ordersM = new \app\admin\model\Orders();
            $row = $ordersM->where('id', $order_id)
                //->where(['status' => 0])
                ->find();
            if (!$row) {
                $this->error('找不到订单信息' . $order_id, $row);
            }
            if ($row['master_id'] == $this->auth->id) {
                $this->error('您已完成接单，请勿重复接单');
            }
            if ($row['assign_status'] != 1) {
                //  $this->success('抱歉，此订单已被接收', ['master' => $row['master'], 'code' => 1]);
            }
            if ($row['master_id'] > 0) {
                $this->success('抱歉，此订单已被接收', ['master' => $row['master'], 'code' => 1]);
            }
            // 加一下所
            $row->master_id = $this->auth->id;
            $row->assign_status = 1;
            $row->status = 1;
            $row->get_time = time();
            $res = $row->save();
            if (!$res) {
                $this->error('接单失败，请重试');
            }
            $this->success('接单成功');
        }
        //申请成接单人员才可以接单
        $this->error('非商家操作' . $this->auth->group_id);
    }


    public function orderDetail()
    {
        $order_id = $this->request->param('order_id/d');
        $rows = (new \app\admin\model\Orders())
            ->with(['business', 'appfuns', 'user'])
            ->where([
                ['id', '=', $order_id],
            ])
            ->find();
        $textarea = json_decode($rows['textarea'], true);
        $formapp = [];

        $canview=false;
        if($this->auth->id==$rows['master_id']){
            $canview=true;
        }
        if (!empty($textarea) && count($textarea) > 0) {
            foreach ($textarea as $k => $v) {
                $formapp[] = ['title' => $v['name'], 'value' => $canview?$v['value']:'***'];
            }
        }
        $rows['formappa'] = $formapp;
        $this->success('', $rows);
    }

    /**
     * 商家取消接单
    */
    public function cancelOrder()
    {
        $order_id = $this->request->param('order_id/d');
        $rows = (new \app\admin\model\Orders())
            ->where([
                ['id', '=', $order_id],
            ])
            ->find();
        if($rows['master_id']!=$this->auth->id){
            $this->error('权限不足');
        }
        $rows->status = 0;
        $rows->assign_status = 0;
        $rows->master_id = 0;
        $rows->get_time =null;
        $rows->save();
        $this->success('取消接单成功',$rows);
    }
}